package com.cashmama.market.api.application.controller;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @program: market-api
 * @description
 * @author: frank
 * @create: 2020-09-24 15:54
 **/
@Service
public class AmazonS3Service {

    /**
     * access_key_id 你的亚马逊S3服务器访问密钥ID
     */
    private static final String ACCESS_KEY = "AKIAWUCLRELHUB4CFU6I";
    /**
     * secret_key 你的亚马逊S3服务器访问密钥
     */
    private static final String SECRET_KEY = "ifmvbwQ8fR7cKC0Y6S3hWTLfj8p9XSjwq5yEK1K7";
    /**
     * end_point 你的亚马逊S3服务器连接路径和端口(新版本不再需要这个,直接在创建S3对象的时候根据桶名和Region自动获取)
     *
     * 格式: https://桶名.s3-你的Region名称.amazonaws.com
     * 示例: https://xxton.s3-cn-north-1.amazonaws.com
     */
//    private static final String END_POINT = "https://xxton.s3-cn-north-1.amazonaws.com";
    /**
     * bucketname 你的亚马逊S3服务器创建的桶名
     */
    private static final String BUCKET_NAME = "cashmama";

    /**
     * 创建访问凭证对象
     */
    private static final BasicAWSCredentials awsCreds = new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY);
    /**
     * 创建s3对象
     */
    private static final AmazonS3 s3 = AmazonS3ClientBuilder.standard()
            .withCredentials(new AWSStaticCredentialsProvider(awsCreds))
            //设置服务器所属地区
            .withRegion(Regions.AP_SOUTH_1)
            .build();


    private static String uploadFile(){
        OSSClient client = new OSSClient("http://oss-ap-south-1.aliyuncs.com", "LTAI4FgSMcfMBpXavW7iuPpM", "mrJeZyMvjH06kz1FqxugnaFqduBczi");
        OSSObject ossObject = client.getObject("cashmama-fat2", "clientSpace/test/2018083199006051000110/1cc2cfbe-3d56-4a3a-a968-68594a83b37f");
        InputStream inputStream = ossObject.getObjectContent();
        ObjectMetadata objectMetadata = new ObjectMetadata();
        PutObjectRequest request = new PutObjectRequest(BUCKET_NAME, "1cc2cfbe-3d56-4a3a-a968-68594a83b37f", inputStream, objectMetadata);
        // 设置公共读取
        request.withCannedAcl(CannedAccessControlList.PublicRead);
        // 上传文件
        PutObjectResult putObjectResult = s3.putObject(request);
        if (null != putObjectResult) {
            return "";
        }
        return "";
    }
    /**
     * 上传文件示例
     *
     * @param uploadPath 上传路径
     */
    private static String uploadFile(File file, String uploadPath) {
        try {
            if (file == null) {
                return null;
            }
            //设置文件目录
            if(StringUtils.isNotEmpty(uploadPath)){
                uploadPath= "/".equals(uploadPath.substring(uploadPath.length()-1))?uploadPath:uploadPath+"/";
            }else{
                uploadPath="default/";
            }
            //生成随机文件名
            String expandedName= file.getName().substring(file.getName().lastIndexOf("."));
            String key = uploadPath + UUID.randomUUID().toString() +expandedName;
            // 设置文件上传对象
            PutObjectRequest request = new PutObjectRequest(BUCKET_NAME, key, file);
            // 设置公共读取
            request.withCannedAcl(CannedAccessControlList.PublicRead);
            // 上传文件
            PutObjectResult putObjectResult = s3.putObject(request);
            if (null != putObjectResult) {
                return key;
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取文件下载路径
     * @param key 文件的key
     * @return
     */
    private static String downloadFile(String key){
        try {
            if(StringUtils.isEmpty(key)){
                return null;
            }
            GeneratePresignedUrlRequest httpRequest = new GeneratePresignedUrlRequest(BUCKET_NAME, key);
            return s3.generatePresignedUrl(httpRequest).toString();
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public static byte[] input2byte(InputStream inStream) throws IOException {
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        int rc = 0;
        while ((rc = inStream.read(buff, 0, 100)) > 0) {
            swapStream.write(buff, 0, rc);
        }
        byte[] in2b = swapStream.toByteArray();
        return in2b;
    }

    public static void main(String[] args){
        OSSClient client = new OSSClient("http://oss-ap-south-1.aliyuncs.com", "LTAIdLWKCjim56VK", "BMZ30CP2IqHupsRwU90AyvXrSf1NfL");
        OSSObject ossObject = client.getObject("cashmama-pro", "moveClientSpace/2018091399006125001410/af5885e7-46ab-4b7e-b1a8-0ea6c0dc6742");
        InputStream inputStream = ossObject.getObjectContent();
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentType("image/jpeg");
        PutObjectRequest request = new PutObjectRequest(BUCKET_NAME, "moveClientSpace/2018091399006125001410/af5885e7-46ab-4b7e-b1a8-0ea6c0dc6742", inputStream, objectMetadata);
        // 设置公共读取
        request.withCannedAcl(CannedAccessControlList.PublicRead);
        // 上传文件
        PutObjectResult putObjectResult = s3.putObject(request);
        System.out.println(JSONObject.toJSONString(putObjectResult));


//        S3ObjectInputStream objectContent = null;
//            S3Object s3Object = s3.getObject(BUCKET_NAME, "moveClientSpace/2020093099009729104510/0dce7cc6624d4c238fc2c87c6de4eb35_B");
//            // 获取Object的输入流
//            objectContent = s3Object.getObjectContent();
//
//        OSSClient client = new OSSClient("http://oss-ap-south-1.aliyuncs.com", "LTAIdLWKCjim56VK", "BMZ30CP2IqHupsRwU90AyvXrSf1NfL");
//        com.aliyun.oss.model.ObjectMetadata meta = new com.aliyun.oss.model.ObjectMetadata();
//            meta.setContentType("image/jpeg");
//        com.aliyun.oss.model.PutObjectResult ossObject = client.putObject("cashmama-pro", "moveClientSpace/2020093099009729104510/0dce7cc6624d4c238fc2c87c6de4eb35_B", objectContent, meta);
//        System.out.println(JSONObject.toJSONString(ossObject));
    }
}
